<?
$postconf = "/etc/postfix/main.cf";

function readConf( $file ) {
	$file = file( $file );
	$settings = array();
	foreach ($file as $line) {
		trim($line);
		if($line[0] != '#') {
			$words = explode(" ", $line);
			if( isset($words[1]) && (trim($words[1]) == '=') ) {
				$key = $words[0];
				$value = implode(" ", array_slice($words, 2));
				$settings[$key] = trim($value);
			}
		}
	}
	return $settings;
}

function showbase( )
{
	global $postconf;
	global $ISPCONF;

	$settings = readConf( $postconf );
	$isps = readConf( $ISPCONF );
	
	  // mydestination - trim och visa inte localhost
	$arr = explode(', ', $settings["mydestination"]);
	$arr = array_map('trim', $arr);
	$nr = array_search('localhost', $arr);
	if( $nr !== FALSE )
		unset( $arr[$nr] );
	$mydestination = $arr;
	
	  // relayhost
	$relayhost = trim($settings["relayhost"]);
	

	echo '<table '.help('base_mynetworks').'>';
	echo '<tr><td class="tbhead">Accepterar mail för dessa domäner</td></tr>';
	foreach( $mydestination AS $dest ) {
		echo '<tr><td>'.$dest.' <a href="?s=mail&amp;t=base&amp;del=mydestination&amp;dest='.$dest.'&amp;do=1" '.confirm('mydestination_del').'><img src="images/delete.png" alt="delete"></a></td></tr>';
	}
	echo '<tr><td><input type="text" name="new_domain">';
	echo   '<input type="submit" class="button" name="b_new_domain" value="lägg till"></td></tr>';
	echo '</table><br>';

	echo '<table '.help('base_mailrelay').'>';
	echo '<tr><td class="tbhead">Mail skickas via&nbsp;&nbsp;&nbsp;&nbsp;(mailrelay)</td></tr>';
	echo '<tr><td><select name="isp" onChange="base_isp_update()">';
	$str = '';
	foreach( $isps AS $path => $name )
		$str .= '<option name="'.$name.'" value="'.$path.'"> '.$name.'</option>';
	$str = str_replace('value="'.$relayhost.'">','value="'.$relayhost.'" selected>', $str, $count);
	if( $count == 0 )
		echo '<option name="other" value="" selected> annan / ingen</option>'.$str;
	else
		echo '<option name="other" value=""> annan / ingen</option>'.$str;
	echo   '</select>';
	echo   ' -> <input type="text" name="relayhost" onKeyDown="document.pageform.isp.selectedIndex=0" value="'.$relayhost.'"></td></tr>';
	echo '</table><br>';
	echo '
<SCRIPT LANGUAGE="JavaScript" type="text/javascript">
<!--
function base_isp_update() {
	document.pageform.relayhost.value = document.pageform.isp.value
}
//-->
</SCRIPT>
';

	
    // SPAMSKYDD
	// Läs in om postfix pratar med spamassassin
	$postmaster = file_get_contents('/etc/postfix/master.cf');
	if( preg_match('/^smtp\s+inet\s+([n-]\s+)+smtpd$\s*\-o\s+content_filter=spamassassin\s*$/m', $postmaster) ) {
		// Läs in gränsvärde för spamskyddet
		$spamlocal = file_get_contents('/etc/spamassassin/local.cf');
		if( preg_match('/^\s*required_score\s+(\S+)\s*$/m', $spamlocal, $matches) )
			$spampoint = intval($matches[1]);
		else {
			//Kunde ej läsa in gränsvärde för spamskydd
			echo '<b style="color:#f00">Fel vid inläsning av spamskydd</b><br>';
			$spampoint = 5;
		}
	}
	else {
		//Spamskydd är inaktiv
		$spampoint = false;
	}
	echo '<table '.help('base_spam').'>';
	echo '<tr><td class="tbhead">Spamskydd</td></tr>';
	echo '<tr><td>spamskyddets aggressivitet <select name="spampoint">';
	echo 	'<option value="1" '.($spampoint==1?'selected':'').'> mycket aggressiv</option>';
	echo 	'<option value="3" '.($spampoint==3?'selected':'').'> aggressiv</option>';
	echo 	'<option value="5" '.($spampoint==5?'selected':'').'> medel</option>';
	echo 	'<option value="7" '.($spampoint==7?'selected':'').'> försiktig</option>';
	echo 	'<option value="9" '.($spampoint==9?'selected':'').'> mycket försiktig</option>';
	echo 	'<option value="false" '.($spampoint===false?'selected':'').'> inaktiv</option>';
	echo 	'</select></td></tr>';
	echo '</table><br>';
}


function showfetch()
{
	$poll = array();

	$fetchmailrc = file("/etc/fetchmailrc");
	foreach( $fetchmailrc AS $line ) {
		if( preg_match("/^poll [^\ ]+ proto [^\ ]+ user \"[^\"]+\" password \"[^\"]+\" is \"[^\"]+\"$/", $line, $arr) ) {
			$poll[] = $arr[0];
		}
		else if( preg_match("/^set daemon \d+$/", $line, $arr) ) {
			$arr = explode(' ', $arr[0]);
			$min = $arr[2]/60;
		}
	}

	echo '<div '.help('fetch_time').'>';
	echo 'Hämta mail var <input type="text" name="pollmin" style="width: 2em; text-align: right" value="'.$min.'"> minut<br><br>';
	echo '</div>';

	echo '<table>';
	echo '<tr><td class="tbhead" style="width: 10em">fjärr-server</td><td class="tbhead" style="width: 10em">fjärr-mailbox</td><td class="tbhead" style="width: 10em">lokal-mailbox</td><td class="tbhead">&nbsp;</td></tr>';
	$i = 0;
	foreach( $poll AS $line ) {
		$i++;
		$bits = explode(' ', $line);
		$host = $bits[1];
		$remote_user = substr($bits[5], 1, -1);
		$local_user = substr($bits[9], 1, -1);
		$post = 'host='.$host.'&amp;remote='.$remote_user.'&amp;local='.$local_user;
		$link = '?s=mail&amp;t=changefetchmail&amp;'.$post;
		echo "<tr ".($i%2==1?"class='list1'":"class='list2'").">\n";
		echo ' <td onClick="location = \''.$link.'\'"><a href="'.$link.'">'.$host.'</a></td>';
		echo ' <td onClick="location = \''.$link.'\'"><a href="'.$link.'">'.$remote_user.'</a></td>';
		echo ' <td onClick="location = \''.$link.'\'"><a href="'.$link.'">'.$local_user.'</a></td>';
		echo ' <td style="text-align: right;"><a href="?s=mail&amp;t=fetchmail&amp;del=fetchpost&amp;'.$post.'&amp;do=1" '.confirm('fetchpost_del').'><img src="images/delete.png" alt="delete"></a></td></tr>';
		echo '</tr>';
	}
	echo '<tr><td colspan=4 style="text-align: right;"><input type="submit" class="button" name="b_new_domain" value="lägg till" '.help('fetch_new').'></td></tr>';
	echo '</table><br>';
}


function showchangefetch()
{
	$protoarr = array('pop3', 'imap');

	if( isset($_GET['remote']) ) {
		$remote = $_GET['remote'];
		echo '<input type="hidden" name="old_remote" value="'.$remote.'">';
	}
	else
		$remote = '';
	if( isset($_GET['local']) ) {
		$local = $_GET['local'];
		echo '<input type="hidden" name="old_local" value="'.$local.'">';
	}
	else
		$local = '';

	if( isset($_GET['host']) ) {
		$host = $_GET['host'];
		$fetchmailrc = file_get_contents("/etc/fetchmailrc");
		if( preg_match("/\npoll $host proto [^\ ]+ user \"$remote\" password \"[^\"]+\" is \"$local\"\n/", $fetchmailrc, $arr) ) {
			$arr = explode(' ', $arr[0]);
			$proto = $arr[3];
		}
		echo '<input type="hidden" name="old_host" value="'.$host.'">';
	}
	else {
		$host = '';
		$proto = 'pop3';
	}

	$passwd = '';

	//Hämta användardata
	$ldap = ldapConnect();
	$userarr = getLdapUsers($ldap);
	ldapClose($ldap);

	//Visa formulär
	echo '<table>';
	echo '<tr><td>fjärr-mailserver</td><td><input type="text" name="host" value="'.$host.'"></td></tr>';
	echo '<tr><td>protokoll</td><td>';

	echo '<select name="proto">';
	echo "<option value=\"$proto\" selected>$proto\n";
	foreach($protoarr as $opt) {
		if( $proto != $opt )
			echo "<option value=\"$opt\">$opt\n";
	}
	echo '</selected>';

	echo '</td></tr>';
	echo '<tr><td>fjärr-mailbox</td><td><input type="text" name="remote" value="'.$remote.'"></td></tr>';
	echo '<tr><td>fjärr-lösen</td><td><input type="password" name="passwd" value="'.$passwd.'"></td></tr>';
	echo '<tr><td>lokal användare</td><td>';
	
	echo '<select name="local">';
	echo "<option value=\"$local\" selected>$local\n";
	foreach($userarr as $user) {
		$username = $user["cn"][0];
		if( $username != $local )
			echo "<option value=\"$username\">$username\n";
	}
	echo '</selected>';

	echo '</td></tr>';
	echo '</table><br>';
}


function showadvanced()
{
	global $postconf;

	$settings = readConf( $postconf );

	$mynetworks = array();
	if( isset($settings["mynetworks"]) ) {
		  // mynetworks - trim och visa inte 127.0.0.0/8
		$arr = explode(', ', $settings["mynetworks"]);
		$arr = array_map('trim', $arr);
		$nr = array_search('127.0.0.0/8', $arr);
		if( $nr !== FALSE )
			unset( $arr[$nr] );
		//$mynetworks = implode(', ', $arr);
		$mynetworks = $arr;
		
	}

	echo '<table>';
	echo '<tr><td class="tbhead">Tillåtna avsändarnät</td></tr>';
	if( isset($settings['mynetworks_style']) )
		echo '<tr><td><input type="checkbox" name="allow_only_own" onClick="advanced_change_allowonlyown()" checked> enbart serverns subnät</td></tr>';
	else
		echo '<tr><td><input type="checkbox" name="allow_only_own" onClick="advanced_change_allowonlyown()"> enbart serverns subnät</td></tr>';
	echo '<tr><td><table id="table_mynetworks">';
	foreach(  $mynetworks AS $network ) {
		echo '<tr><td>'.$network.' <a href="main.php?s=mail&amp;t=advanced&amp;del=mynetworks&amp;net='.$network.'&amp;do=1"><img src="images/delete.png" alt="delete"></a></td></tr>';
	}
	echo '</table></td></tr>';
	echo '<tr><td><input type="text" name="new_net_allow">';
	echo '<input type="submit" class="button" name="b_new_net" value="lägg till"></td></tr>';
	echo '</table><br>';
	echo '
<script type="text/javascript">
<!--
function advanced_change_allowonlyown() {
	if (document.pageform.allow_only_own.checked==true) {
		document.pageform.new_net_allow.disabled=true
		document.pageform.b_new_net.disabled=true
		document.getElementById("table_mynetworks").style.visibility="collapse"
	}
	else {
		document.pageform.new_net_allow.disabled=false
		document.pageform.b_new_net.disabled=false
		document.getElementById("table_mynetworks").style.visibility="visible"
	}
}
advanced_change_allowonlyown()
//-->
</script>
';

    // Komma skall
	/*echo '<table>';
	echo '<tr><td class="tbhead">Protokoll</td></tr>';
	echo '<tr><td><input type="checkbox" name="pop3"> pop3</td></tr>';
	echo '<tr><td><input type="checkbox" name="pop3s"> pop3/ssl</td></tr>';
	echo '<tr><td><input type="checkbox" name="imap"> imap</td></tr>';
	echo '<tr><td><input type="checkbox" name="imaps"> imap/ssl</td></tr>';
	echo '</table><br>';
	
	echo '<table>';
	echo '<tr><td class="tbhead" colspan=2>Certifikatnycklar</td></tr>';
	echo '<tr><td>Privat</td><td><input type="input"></td></tr>';
	echo '<tr><td>Publik</td><td><input type="input"></td></tr>';
	echo '</table><br>';*/
}


function showemailgroups() {
	echo '
		<table><tr><td class="tbhead">Gruppmail</td></tr><tr><td>
		Mailadresser du skapar här kan gå till flera olika mottagare.
		</td></tr></table><br>
	';

	echo   '<input '.help('emailgroups_add').' type="submit" class="button" name="b_new_emailgroup" value="Skapa ny"><br><br>';

	$path = '/etc/postfix/emailgroups';
	if (!file_exists($path))
		touch($path);
	$strall = file_get_contents($path);
	$lines = explode("\n", trim($strall));
	if ($lines[0] == '')
		unset($lines[0]);

	$i=0;
	echo '<table><tr><td>';
	foreach ($lines as $l) {
		$checkbox = 'checked';
		$disabled = 'background-color:#cce';
		list($name, $addr) = split(': ', $l);
		if (substr($name,0,1) == '#') {
			$name = substr($name,1);
			$checkbox='';	
			$disabled='background-color:#aaa;';	
		}
		echo '
			<table style="'.$disabled.'; border:1px solid #666; margin-bottom:10px;"><tr>
			<td style="vertical-align:top"><span '.help('emailgroups_name').'>Gruppmailadress: <input name="name_'.$i.'" value="'.$name.'"></input></span> <span '.help('emailgroups_active').'>Aktiv: <input name="active_'.$i.'" type="checkbox" '.$checkbox.'></input></span></td>
			<td><input type="submit" '.confirm('emailgroups_del').' name="b_delete_'.$i.'" value="" style="cursor:pointer; background:url(images/delete.png) no-repeat; border:0px; width:10px; height:10px; float:right;"></td>
			</tr><tr>
			<td colspan="2"><textarea '.help('emailgroups_addr').' name="addr_'.$i.'" style="width:600px; height:100px;">'.$addr.'</textarea></td>
			</tr></table>';
		$i++;
	}
	echo '</td></tr></table>';
	echo '<input type="hidden" name="entries" value="'.$i.'">';
	if ($i > 0)
		echo '<input type="submit" class="buttonlong" name="b_OK" value="Utför ändringar"><br><br>';
}

////////////////////////////
////////////////////////////


$tabsmain = array( 
	array('base','Grundinställningar'), 
	array('fetchmail','Fjärrhämtning'), 
	array('emailgroups','Gruppmail'), 
	array('advanced','Avancerat') 
	);
$tabschangefetch = array(
	array('fetchmail', 'Fjärrhämtning')
	);

$t='';
if( isset($_GET['t']) ) $t=$_GET['t'];
switch( $t ) {
default:
case 'base':
	html_start( $tabsmain );
	showbase();
	html_end(true, true, true);
	break;
case 'fetchmail':
	html_start( $tabsmain );
	showfetch();
	html_end(true, true, true);
	break;
case 'changefetchmail':
	html_start( $tabschangefetch );
	showchangefetch();
	html_end(true, false, true, 'mail', 'fetchmail');
	break;
case 'advanced':
	html_start( $tabsmain );
	showadvanced();
	html_end(true, true, true);
	break;
case 'emailgroups':
	html_start( $tabsmain );
	showemailgroups();
	html_end();
	break;
}



?>
